package xg.glycomaid;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.net.URL;

import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

class OutputTableRenderer extends DefaultTableCellRenderer implements MouseListener, MouseMotionListener {
    private static Rectangle lrect = new Rectangle();
    private static Rectangle irect = new Rectangle();
    private static Rectangle trect = new Rectangle();
    private int row = -1;
    private int col = -1;
    private boolean isRollover = false;
    private static final Color evenColor = new Color(250,250,250);
    
   // @Override 

    
    public Component getTableCellRendererComponent(JTable table, Object value,
                                                   boolean isSelected, boolean hasFocus,
                                                   int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected, false, row, column);

        this.setForeground(Color.black);
        this.setBackground((row%2==0)?evenColor:Color.white);
        
        if(isSelected)
        	 this.setBackground(Color.lightGray);
        //background color differ between two neighbour rows


        //TEST: this.setBorder(BorderFactory.createMatteBorder(0,16,0,16,Color.RED));
        if(isURLColumn(table, column)){
            int mw = table.getColumnModel().getColumnMargin();
            int rh = table.getRowMargin();
            int w  = table.getColumnModel().getColumn(column).getWidth();
            int h  = table.getRowHeight(row);
        	
        	Insets i = this.getInsets();
        	lrect.x = i.left;
        	lrect.y = i.top;
        	lrect.width  = w - (mw + i.right  + lrect.x);
        	lrect.height = h - (rh + i.bottom + lrect.y);
        	irect.x = irect.y = irect.width = irect.height = 0;
        	trect.x = trect.y = trect.width = trect.height = 0;

        	String str = SwingUtilities.layoutCompoundLabel(
        			this,
        			this.getFontMetrics(this.getFont()),
        			value==null?"":this.getCarbID(value),
        			this.getIcon(),
        			this.getVerticalAlignment(),
        			this.getHorizontalAlignment(),
        			this.getVerticalTextPosition(),
        			this.getHorizontalTextPosition(),
        			lrect,
        			irect, //icon
        			trect, //text
        			this.getIconTextGap());
        	//String str = value!=null?value.toString():"";

        	if(!table.isEditing() && this.row==row && this.col==column && this.isRollover) {
        		setText("<html><u><font color='blue'>"+str);
//  	       }else if(hasFocus) {
//     	        setText("<html><font color='blue'>"+str);
        	}else{
        		setText(str);
        	}
        }
        return this;
    }
    private String getCarbID(Object value) {

    	if(value.toString().contains("=carb"))
    	{
        	return value.toString().substring(value.toString().indexOf("=carb")+1, value.toString().indexOf("&sideMenu"));
    	}
    	else return "URL error";
    	
	}
	//@see SwingUtilities2.pointOutsidePrefSize(...)
    private static boolean pointInsidePrefSize(JTable table, Point p) {
        int row = table.rowAtPoint(p);
        int col = table.columnAtPoint(p);
        TableCellRenderer tcr = table.getCellRenderer(row, col);
        Object value = table.getValueAt(row, col);
        Component cell = tcr.getTableCellRendererComponent(table, value, false, false, row, col);
        Dimension itemSize = cell.getPreferredSize();
        Insets i = ((JComponent)cell).getInsets();
        Rectangle cellBounds = table.getCellRect(row, col, false);
        cellBounds.width = itemSize.width-i.right-i.left;
        cellBounds.translate(i.left, i.top);
        return cellBounds.contains(p);
    }
    
    private static boolean isURLColumn(JTable table, int column) {
        return column>=0 && table.getColumnClass(column).equals(URL.class);
    }
    
    
    
    //@Override
    public void mouseMoved(MouseEvent e) {
        JTable table = (JTable)e.getSource();
        Point pt = e.getPoint();
        int prev_row = row;
        int prev_col = col;
        boolean prev_ro = isRollover;
        row = table.rowAtPoint(pt);
        col = table.columnAtPoint(pt);
        isRollover = isURLColumn(table, col) && pointInsidePrefSize(table, pt);
        if((row==prev_row && col==prev_col && isRollover==prev_ro) || (!isRollover && !prev_ro)) {
            return;
        }
// >>>> HyperlinkCellRenderer.java
// @see http://java.net/projects/swingset3/sources/svn/content/trunk/SwingSet3/src/com/sun/swingset3/demos/table/HyperlinkCellRenderer.java
        Rectangle repaintRect;
        if(isRollover) {
            Rectangle r = table.getCellRect(row, col, false);
            repaintRect = prev_ro ? r.union(table.getCellRect(prev_row, prev_col, false)) : r;
        }else{ //if(prev_ro) {
            repaintRect = table.getCellRect(prev_row, prev_col, false);
        }
        table.repaint(repaintRect);
// <<<<
        //table.repaint();
    }
    
    //@Override 
    public void mouseExited(MouseEvent e)  {
        JTable table = (JTable)e.getSource();
        if(isURLColumn(table, col)) {
            table.repaint(table.getCellRect(row, col, false));
            row = -1;
            col = -1;
            isRollover = false;
        }
    }
    //@Override 
    public void mouseClicked(MouseEvent e) {
        JTable table = (JTable)e.getSource();
        Point pt = e.getPoint();
        int ccol = table.columnAtPoint(pt);
        int crow = table.rowAtPoint(pt);

        if(isURLColumn(table, ccol) && pointInsidePrefSize(table, pt)) {

            URL url = (URL)table.getValueAt(crow, ccol);
            System.out.println(url);
            try{
                //Web Start
                //BasicService bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService");
                //bs.showDocument(url);
                if(Desktop.isDesktopSupported()) { // JDK 1.6.0
                    Desktop.getDesktop().browse(url.toURI());
                }
            }catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }
   // @Override 
    public void mouseDragged(MouseEvent e) {}
   // @Override 
    public void mouseEntered(MouseEvent e) {}
    //@Override 
    public void mousePressed(MouseEvent e) {
    }   
    
   // @Override 
    public void mouseReleased(MouseEvent e) {}

}